package dao;

import java.sql.*;
import java.util.ArrayList;

import bean.User;
import util.DBUtil;

public class UserDao {
	DBUtil db=new DBUtil();
	Connection conn=db.open();
	PreparedStatement pstmt=null;
	ResultSet rs=null;
	User user =new User();
	public User findByName(String userName){
		
		if(userName==null){
			return null;
		}
		try {
			
			String sql="SELECT * FROM user WHERE user_name='"+userName+"'";
			
			pstmt=conn.prepareStatement(sql);
			rs=pstmt.executeQuery();
			while(rs.next()){
				user.setId(rs.getInt(1));
				user.setPassWord(rs.getString("password"));
				user.setUserName(rs.getString("user_name"));
				return user;
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException("数据库连接失败");
		}finally{
			db.close();
		}
		return null; 
	}
	public void regist(User user){
		
		String sql="insert into user(user_name,password,role,safe_problem,safe_answer,safe_hint,email,states) values(?,?,?,?,?,?,?,?)";
		try {
			pstmt=conn.prepareStatement(sql);
			pstmt.setString(1, user.getUserName());
			pstmt.setString(2, user.getPassWord());
			pstmt.setString(3, user.getRole());
			pstmt.setString(4, user.getSafeProbelm());
			pstmt.setString(5, user.getSafeAnswer());
			pstmt.setString(6, user.getHint());
			pstmt.setString(7, user.getEmail());
			pstmt.setString(8, user.getState());
			
			pstmt.executeUpdate();
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			db.close();
		}
	}
	//修改密码
	public void ChangePwd(User user1){
		String sql="update user set password=? where id="+user1.getId();
		try {
			pstmt=conn.prepareStatement(sql);
			pstmt.setString(1, user1.getPassWord());
//			pstmt.setString(2, user.getUserName());
//			pstmt.setString(3, user.getPassWord());
			pstmt.executeUpdate();
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			db.close();
		}
	}
	//修改安全问题
	public void ChangeSapro(User user2){
		String sql="update user set safe_problem=?,safe_answer=?,safe_hint=?where id="+user2.getId();
		try {
			pstmt=conn.prepareStatement(sql);
			pstmt.setString(1, user2.getSafeProbelm());
			pstmt.setString(2, user2.getSafeAnswer());
			pstmt.setString(3, user2.getHint());
			pstmt.executeUpdate();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
